package hsp.admin.app.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hsp.admin.api.ApiResult;
import hsp.admin.app.base.po.RolePO;
import hsp.admin.app.base.service.IRoleService;
import hsp.admin.enums.Status;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Tag(name = "RoleController", description = "角色管理")
@RestController
@RequestMapping("base/role")
public class RoleController {

    private final IRoleService service;

    @Autowired
    public RoleController(IRoleService service){
        this.service = service;
    }

    @Operation(summary = "获取角色")
    @GetMapping("{id}")
    public ApiResult<RolePO> getRole(@PathVariable("id") long id){
        RolePO po = service.getById(id);
        return ApiResult.success(po);
    }

    @Operation(summary = "获取角色分页")
    @GetMapping("page/{page}/{size}")
    public ApiResult<Page<RolePO>> getRolePage(@PathVariable("page")int page, @PathVariable("size")int size, RolePO po){
        LambdaQueryWrapper<RolePO> wrapper = new LambdaQueryWrapper<>();
        if(po.getId() != null) wrapper.eq(RolePO::getId, po.getId());
        if(StringUtils.isNotBlank(po.getName())) wrapper.like(RolePO::getName, po.getName());
        if(StringUtils.isNotBlank(po.getStatus())) wrapper.eq(RolePO::getStatus, po.getStatus());
        wrapper.orderByAsc(RolePO::getOrdIdx);
        Page<RolePO> baseRolePOPage = service.page(new Page<>(page, size), wrapper);
        return ApiResult.success(baseRolePOPage);
    }

    @Operation(summary = "编辑角色")
    @PostMapping()
    public ApiResult<?> postOrPutRole(@RequestBody RolePO po){
        service.saveOrUpdate(po);
        return ApiResult.success();
    }

    @Operation(summary = "删除角色")
    @DeleteMapping("{id}")
    public ApiResult<?> deleteRole(@PathVariable("id") long id){
        service.removeById(id);
        return ApiResult.success();
    }

    @Operation(summary = "获取角色列表")
    @GetMapping("list")
    public ApiResult<List<RolePO>> getRoleList(){
        LambdaQueryWrapper<RolePO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePO::getStatus, Status.Enabled.getCode());
        List<RolePO> list = service.list(wrapper);
        return ApiResult.success(list);
    }

}
